// file客户端程序，对文件存储子服务进行单元测试

#include <gflags/gflags.h>
#include <gtest/gtest.h>
#include <thread>
#include "etcd.hpp"
#include "channel.hpp"
#include "logger.hpp"
#include "file.pb.h"
#include "base.pb.h"
#include "utils.hpp"
#include "logger.hpp"

DEFINE_bool(run_mode, false, "程序的运行模式，false-调试； true-发布；");
DEFINE_string(log_file, "", "发布模式下，用于指定日志的输出文件");
DEFINE_int32(log_level, 0, "发布模式下，用于指定日志输出等级");

DEFINE_string(etcd_host, "http://127.0.0.1:2379", "服务注册中心地址");
DEFINE_string(base_service, "/service", "服务监控根目录");
DEFINE_string(file_service, "/service/file_service", "服务监控根目录");

chen_im::ServiceChannel::ChannelPtr channel;
std::string single_file_id;

TEST(put_test, single_file)
{
    //读取当前目录下的指定文件数据
    std::string body;
    ASSERT_TRUE(chen_im::readFile("./Makefile", body));
    //2实例化rpc调用客户端对象, 发起rpc调用
    chen_im::FileService_Stub stub(channel.get());

    chen_im::PutSingleFileReq req;
    req.set_request_id("1111");
    req.mutable_file_data()->set_file_name("Makefile");
    req.mutable_file_data()->set_file_size(body.size());
    req.mutable_file_data()->set_file_content(body);

    brpc::Controller* cntl = new brpc::Controller();
    chen_im::PutSingleFileRsp* rsp = new chen_im::PutSingleFileRsp();
    stub.PutSingleFile(cntl, &req, rsp, nullptr);
    ASSERT_FALSE(cntl->Failed());
    //检查返回值上传是否成功

    //3. 检测返回值中上传是否成功
    ASSERT_TRUE(rsp->success());
    ASSERT_EQ(rsp->file_info().file_size(), body.size());
    ASSERT_EQ(rsp->file_info().file_name(), "Makefile");
    single_file_id = rsp->file_info().file_id();
    LOG_DEBUG("文件ID：{}", rsp->file_info().file_id());
}


int main(int argc, char* argv[])
{
    testing::InitGoogleTest(&argc, argv);
    google::ParseCommandLineFlags(&argc, &argv, true);

    chen_im::init_logger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);

    //1, 先构造Rpc信道管理对象
    auto sm = std::make_shared<chen_im::ServiceManager>();
    sm->declared(FLAGS_file_service);
    auto put_cb = std::bind(&chen_im::ServiceManager::onServiceOnline, sm.get(), std::placeholders::_1, std::placeholders::_2);
    auto del_cb = std::bind(&chen_im::ServiceManager::onServiceOffline, sm.get(), std::placeholders::_1, std::placeholders::_2);

    chen_im::Discovery::ptr dclient = std::make_shared<chen_im::Discovery>(FLAGS_etcd_host, FLAGS_base_service, put_cb, del_cb);

    channel = sm->choose(FLAGS_file_service);
    if(!channel)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        return -1;
    }

    return RUN_ALL_TESTS();
}


